<!--
 * @description 定向福利-新增页
 * @author dumeng
 * @date 2021/7/28
 -->
<template>
  <div class="derectional-create-page">
    <el-steps class="comment-step" :active="stepActive" simple>
      <el-step v-for="(item, index) in stepList" :key="index" :title="item.title" :status="item.status" />
    </el-steps>
    <el-scrollbar class="classify-scrollbar">
      <template v-if="stepActive === 0">
        <div class="create-title">新建</div>
        <el-form ref="form" class="create-form" :model="form" :rules="rules" label-width="180px">
          <el-form-item label="发放名称" prop="giveName">
            <el-input v-model.trim="form.giveName" placeholder="请输入发放名称" />
          </el-form-item>
          <el-form-item label="选择商城" prop="storeName">
            <el-radio-group v-model="form.storeName" :disabled="!!form.id" @change="changeStore">
              <el-radio v-for="(item,index) in mallTypes" :key="index" :label="item.id">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="福利类型" prop="classifType">
            <el-radio-group
              v-if="form.storeName===1"
              v-model="form.classifType"
              :disabled="!!form.id"
              @change="changeType"
            >
              <el-radio v-for="(item, index) in ptTypes" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
            <el-radio-group
              v-if="form.storeName===2"
              v-model="form.classifType"
              :disabled="!!form.id"
              @change="changeType"
            >
              <el-radio v-for="(item, index) in jdTypes" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
            <el-radio-group
              v-if="form.storeName===3"
              v-model="form.classifType"
              :disabled="!!form.id"
              @change="changeType"
            >
              <el-radio v-for="(item, index) in hfTypes" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <ptflb
            v-if="form.classifType==='0'"
            :id="form.id"
            ref="ptflbForm"
            :data="subForm"
            @useRangeChange="useRangeChange"
          />
          <ptdhq v-if="form.classifType==='1'" :id="form.id" ref="ptdhqForm" :data="subForm" @saveForm="saveForm" />
          <jdflb v-if="form.classifType==='2'" :id="form.id" ref="jdflbForm" :data="subForm" />
          <ptthq v-if="form.classifType==='7'" :id="form.id" ref="ptthqForm" :data="subForm" />
          <hfflb v-if="form.classifType==='8'" :id="form.id" ref="hfflbForm" :data="subForm" />
          <el-form-item class="form-btns">
            <el-button type="primary" @click="onSubmit">确定并进入人员设置</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </template>
      <insert-person
        v-else-if="stepActive === 1"
        :id="form.id"
        :type="form.classifType"
        :range="useRange"
        @setStep="setStep"
        @isSetPerson="isSetPerson"
      />
      <special-area
        v-else
        :id="form.id"
        :is-set-person="setPerson"
        :give-name="form.giveName"
        :info="areaInfo"
        @setStep="setStep"
        @setInfo="setAreaInfo"
      />
    </el-scrollbar>
  </div>
</template>

<script>
import ptflb from '../components/ptflb'
import ptdhq from '../components/ptdhq'
import ptthq from '../components/ptthq'
import jdflb from '../components/jdflb'
import hfflb from '../components/hfflb'
import insertPerson from '../components/insertPerson'
import SpecialArea from '../components/specialArea'
import { getConfigByName, get, insert } from '../api/index'
export default {
  name: 'DerectionalCreate',
  components: { SpecialArea, ptflb, ptdhq, ptthq, jdflb, hfflb, insertPerson },
  data() {
    return {
      stepList: [
        {
          title: '新建福利发放',
          status: ''
        },
        {
          title: '人员设置',
          status: ''
        },
        {
          title: '专区/商品设置',
          status: ''
        }
      ],
      stepActive: 0,
      form: {
        id: '',
        giveName: '',
        storeName: 1,
        classifType: '0'
      },
      rules: {
        giveName: [
          { required: true, message: '请输入发放名称', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请选择商城', trigger: 'blur' }
        ],
        classifType: [{
          required: true,
          message: '请选择福利类型',
          trigger: 'change'
        }]
      },
      mallTypes: [
      ],
      ptTypes: [],
      jdTypes: [],
      hfTypes: [],
      subForm: {},
      areaInfo: {},
      setPerson: false, // 第二步是否已经设置人员
      useRange: '', // 使用范围
      couponBack: false// 是否是优惠券页面返回的

    }
  },
  watch: {
    'form.classifType': {
      handler: function() {
        if (this.form.classifType === '0') {
          this.stepList = [
            {
              title: '新建福利发放',
              status: ''
            },
            {
              title: '人员设置',
              status: ''
            },
            {
              title: '专区/商品设置',
              status: ''
            }
          ]
        } else {
          this.stepList = [
            {
              title: '新建福利发放',
              status: ''
            },
            {
              title: '人员设置',
              status: ''
            }
          ]
        }
      }
    }
  },
  created() {
    this.getClassType().then(() => {
      if (this.$route.query.t && !this.couponBack) {
        if (this.$route.query.t != '0,2') {
          if (this.$route.query.t === '2') {
            this.form.storeName = 2
          }
          this.form.classifType = this.$route.query.t
        }
      }
    })
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.path === '/welfare/directional/manage') {
        // 取出allForm 进行赋值
        const data = JSON.parse(sessionStorage.getItem('allForm'))
        for (const i in data) {
          if (vm.form.hasOwnProperty(i)) {
            vm.form[i] = data[i] || ''
          } else {
            vm.$set(vm.subForm, i, data[i])
          }
        }
        vm.couponBack = true
        sessionStorage.removeItem('allForm')
      }
    })
  },
  methods: {
    // 保存Form
    saveForm(subForm) {
      if (subForm.receiveTime) {
        subForm.receiveStarttime = subForm.receiveTime[0]
        subForm.receiveEndtime = subForm.receiveTime[1]
        delete subForm.receiveTime
      }
      if (subForm.useTime) {
        subForm.expirationStartdate = subForm.useTime[0]
        subForm.expirationDate = subForm.useTime[0]
        delete subForm.useTime
      }
      sessionStorage.setItem('allForm', JSON.stringify(Object.assign(this.form, subForm)))
    },
    getClassType() {
      return new Promise((resolve, reject) => {
        getConfigByName({ name: 'WELFARE_SHOP_MALL_SHOW' }).then(res => {
          const str = res.data.data.configValue
          if (str.indexOf('0') > -1 || str.indexOf('1') > -1 || str.indexOf('7') > -1) {
            this.mallTypes.push({
              name: '平台商城',
              id: 1
            })
          }
          if (str.indexOf('0') > -1) {
            this.ptTypes.push({
              name: '福利包',
              id: '0'
            })
          }
          if (str.indexOf('2') > -1) {
            this.mallTypes.push({
              name: '京东商城',
              id: 2
            })
            this.jdTypes.push({
              name: '福利包',
              id: '2'
            })
          }
          if (str.indexOf('8') > -1) {
            this.mallTypes.push({
              name: '惠福商城',
              id: 3
            })
            this.hfTypes.push({
              name: '福利包',
              id: '8'
            })
          }
          if (str.indexOf('1') > -1) {
            this.ptTypes.push({
              name: '兑换券',
              id: '1'
            })
          }
          if (str.indexOf('7') > -1) {
            this.ptTypes.push({
              name: '线下提货券',
              id: '7'
            })
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 保存专区信息
     */
    setAreaInfo(info) {
      this.areaInfo = Object.assign({}, info)
    },
    handleCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: { t: this.$route.query.t }
      })
    },
    changeStore(e) {
      if (e === 1) {
        this.form.classifType = '0'
      } else if (e === 2) {
        this.form.classifType = '2'
      } else if (e === 3) {
        this.form.classifType = '8'
      }
    },
    /**
     * 切换福利类型
     */
    async changeType(val) {

    },
    onSubmit() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          if (this.form.classifType === '0') {
            this.subForm = await this.$refs['ptflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            delete this.subForm.merchant
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '福利领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '福利使用结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.receiveStarttime).getTime() > new Date(this.subForm.receiveEndtime).getTime()) {
              this.$message({
                message: '福利领取开始时间不得大于福利领取结束时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationStartdate).getTime() > new Date(this.subForm.expirationDate).getTime()) {
              this.$message({
                message: '福利使用开始时间不得大于福利使用结束时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationStartdate).getTime() < new Date(this.subForm.receiveStarttime).getTime()) {
              this.$message({
                message: '福利使用开始时间不得小于福利领取开始时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date(this.subForm.expirationStartdate).getTime()) {
              this.$message({
                message: '福利使用结束时间不得小于福利领取结束时间！',
                type: 'warning'
              })
              return
            }
          } else if (this.form.classifType === '1') {
            this.subForm = await this.$refs['ptdhqForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券已过期，请选择其他兑换券！',
                type: 'warning'
              })
              return
            }
          } else if (this.form.classifType === '2') {
            this.subForm = await this.$refs['jdflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '京东活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '京东活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
          } else if (this.form.classifType === '7') {
            this.subForm = await this.$refs['ptthqForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
            this.subForm.userUpperLimit = 1
          } else if (this.form.classifType === '8') {
            this.subForm = await this.$refs['hfflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '惠福专区活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '惠福专区活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
          }
          this.createData()
        }
      })
    },
    createData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const params = Object.assign(this.form, this.subForm)
      return new Promise((resolve, reject) => {
        insert(params).then((res) => {
          loading.close()
          if (res.data.code === '200') {
            this.$message({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            if (this.form.id === '') {
              this.$set(this.form, 'id', res.data.data)
            }
            this.setStep(1)
          } else {
            this.$message({
              title: '失败',
              message: res.data.msg || '添加失败',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    setStep(i) {
      if (i === 0) {
        this.getInfo()
      }
      this.stepList.forEach((item, index) => {
        item.status = ''
        if (index < i) {
          item.status = 'success'
        }
      })
      this.stepActive = i
    },
    getInfo() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(this.form.id).then(async res => {
          loading.close()
          const data = res.data.data
          for (const i in data) {
            if (this.form.hasOwnProperty(i)) {
              this.form[i] = data[i]
            } else {
              this.$set(this.subForm, i, data[i])
            }
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 第二步是否已经设置人员
     */
    isSetPerson(s) {
      this.setPerson = s
    },
    /**
     * 监听
     * @param range
     */
    useRangeChange(range) {
      this.useRange = range
      if (this.useRange !== '2') {
        this.stepList = [
          {
            title: '新建福利发放',
            status: ''
          },
          {
            title: '人员设置',
            status: ''
          },
          {
            title: '专区/商品设置',
            status: ''
          }
        ]
      } else {
        this.stepList = [
          {
            title: '新建福利发放',
            status: ''
          },
          {
            title: '人员设置',
            status: ''
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss">
.derectional-create-page {
  padding: 10px;

  .area{
    max-height: 98vh;
    img{
      width: 150px;
      height: 150px;
    }
  }
  .el-dialog .el-dialog__body{
    max-height: 76vh;
  }
  .el-dialog .el-dialog__footer{
    text-align: center;
  }

  .comment-step {
    background-color: #fff;
  }

  .classify-scrollbar {
    background-color: #fff;
    margin-top: 10px;
    height: calc(100vh - 140px);
    .create-title {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #e5e5e5;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;

      &:before {
        content: "";
        position: absolute;
        width: 2px;
        @include bg-color($mainColor);
        top: 13px;
        bottom: 13px;
        left: 15px;
      }
    }

    .create-form {
      width: 1000px !important;
      margin: 20px auto 0;

      .el-select {
        width: 100%;
      }

      .form-btns {
        text-align: center;
      }
    }
  }

}
</style>
